package io.github.tangwan.algorithm;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author tangwan
 * @version V1.0
 * created on 2021/10/8 14:49
 * @since JDK 1.8
 */
public class 两数之和 {

    public static void main(String[] args) {
        int[] ints = twoSum(new int[]{2, 7, 11, 15}, 9);
        System.out.println(Arrays.toString(ints));
    }

    public static int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int sub = target - nums[i];
            if (map.containsKey(sub)){
                return new int[]{map.get(sub),i};
            }
            map.put(nums[i],i);
        }
        return new int[0];
    }

}
